package com.turing.post.tuxedo.service;

import javax.ejb.Remote;
import javax.ejb.RemoteHome;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.naming.Context;
import javax.naming.InitialContext;

import weblogic.ejb.GenericSessionBean;
import weblogic.wtc.jatmi.Reply;
import weblogic.wtc.jatmi.TPException;
import weblogic.wtc.jatmi.TPServiceInformation;
import weblogic.wtc.jatmi.TypedCArray;

import com.turing.post.tuxedo.util.LocalService;
import com.turing.post.tuxedo.util.TransRequest;
import com.turing.post.util.HexDump;
import com.turing.post.util.PCPSUtil;

@SuppressWarnings("serial")
@Stateless(mappedName = "TUXEDO.PCPS.SERVICEENTRY")
@Remote(weblogic.wtc.jatmi.TuxedoService.class)
@RemoteHome(weblogic.wtc.jatmi.TuxedoServiceHome.class)
public class ServiceEntry extends GenericSessionBean {
	/**
	 * PCPS TUXEDO服务入口
	 * 
	 * @param si
	 * @return
	 * @throws TPException
	 */
	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public Reply service(TPServiceInformation si) throws TPException {
		TypedCArray data;
		TypedCArray return_data;
		Context ctx = null;

		data = (TypedCArray) si.getServiceData();

		try {
			// 交易入口 -- 开始跟踪
			PCPSUtil.setTuxedoLogEntry();

			PCPSUtil.Log("PCPS tuxedo service called");

			// 执行具体服务类的服务方法
			if (data != null && data.carray != null)
				PCPSUtil.Log(HexDump.EOL + "PCPS request data LEN "
						+ data.carray.length + HexDump.EOL
						+ HexDump.dump(data.carray, 0, 0));

			// 根据输入的字节数组,获得交易码
			String trancode = TransRequest.getTranCodeFromBuffer(data.carray);

			// 根据交易码查找具体的服务实例EJB
			LocalService svcimpl = null;

			ctx = new InitialContext();
			String name = "PCPS.SVC" + trancode + "#"
					+ LocalService.class.getName();

			try {
				svcimpl = (LocalService) ctx.lookup(name);
				PCPSUtil.Log(svcimpl.getClass().getName());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				PCPSUtil.Log(name + " is null!", e);
				throw new TPException(TPException.TPENOENT, "SVC" + trancode
						+ " SERVICE NOT FOUND!");
			}

			PCPSUtil.Log("Service");

			// 设置返回对象
			return_data = new TypedCArray();

			return_data.carray = svcimpl.Service(data.carray);

			if (return_data != null && return_data.carray != null) {
				PCPSUtil.Log(HexDump.EOL + "PCPS response data LEN "
						+ return_data.carray.length + HexDump.EOL
						+ HexDump.dump(return_data.carray, 0, 0));
			}

			// 设置返回数据的长度
			return_data.setSendSize(return_data.carray.length);

			// 释放上下文对象
			ctx.close();

			// 控制返回到WTC
			si.setReplyBuffer(return_data);

			return (si);
		} catch (Exception ex_) {
			PCPSUtil.Log("ServiceEntry Exception!!!", ex_);
			throw new TPException(TPException.TPESYSTEM,
					"ServiceEntry Exception!!!");
		} finally {
			try {
				if (ctx != null)
					ctx.close();
			} catch (Exception e) {
			}
		}
	}
}